(function() {
  var root = this;

  var previousTool = root.Tool;

  var ArrayProto = Array.prototype,
    ObjProto = Object.prototype,
    FuncProto = Function.prototype;

  var Tool = function(obj) {
    if (obj instanceof Tool) return obj;
    if (!(this instanceof Tool)) return new Tool(obj);
    this._tool = obj;
  };
  //是否可以通过exports暴露
  if (typeof exports !== 'undefined') {
    if (typeof module !== 'undefined' && module.exports) {
      exports = module.exports = Tool;
    }
    exports.Tool = Tool;
  } else {
    root.Tool = Tool;
  }

  /**
   * cookie operation
   **/
  Tool.cookie = {
    set: function(objName, objValue, objHours) {
      var str = objName + "=" + escape(objValue);
      if (objHours > 0) { //为0时不设定过期时间，浏览器关闭时cookie自动消失
        var date = new Date();
        var ms = objHours * 3600 * 1000;
        date.setTime(date.getTime() + ms);
        str += "; expires=" + date.toGMTString() + "; path=/";
      }
      document.cookie = str;
    },
    get: function(objName) {
      var arrStr = document.cookie.split("; ");
      for (var i = 0; i < arrStr.length; i++) {
        var temp = arrStr[i].split("=");
        if (temp[0] == objName)
          return unescape(temp[1]);
      }
    },
    // cookie 删除失效
    del: function(name) {
      var date = new Date();
      date.setTime(date.getTime() - 10000);
      document.cookie = name + "=a; expires=" + date.toGMTString() + "; path=/";
    },
    getItem: function(name, item) {
      var json = eval("(" + this.get(name) + ")");
      return json[item];
    }
  };

  /**
   * localStorage 操作
   */
  Tool.localStorage = {
    set: function(key, value) {
      if (arguments.length === 1 && Object.prototype.toString.call(key).slice(8, -1) == 'Object') {
        for (var name in key) {
          if (Object.prototype.toString.call(key[name]).slice(8, -1) == 'Object') key[name] = JSON.stringify(key[name]);
          getLocalStroage().setItem(name, key[name]);
        }
      } else {
        if (Object.prototype.toString.call(value).slice(8, -1) == 'Object') value = JSON.stringify(value);
        getLocalStroage().setItem(key, value);
      }
      return this;
    },
    get: function(key) {
      if (isExist(key)) {
        var value = getLocalStroage().getItem(key);
        try {
          return JSON.parse(value) || null;
        } catch (e) {
          return value || null;
        }
      }
    },
    remove: function(key) {
      if (isExist(key)) {
        getLocalStroage().removeItem(key);
      }
      return this;
    }
  };

  // getQueryString
  Tool.getQueryString = function(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    // if (r != null) return unescape(r[2]);
    if (r != null) return decodeURIComponent(r[2]);
    return null;
  };
})();
